#include "messageeditarea.h"
#include <QMessageBox>
#include"mainwidget.h"

MessageEditArea::MessageEditArea(QWidget *owner)
    :owner(owner)
{
    // 1. 设置基础属性
    this->setFixedHeight(150);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    this->setObjectName("editArea");
    this->setStyleSheet("#editArea { border-left: 1px solid #D5D5D5; }");

    // 2. 创建垂直布局管理器
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setContentsMargins(10, 0, 10, 10);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);
    this->setLayout(layout);

    // 3. 创建⼯具按钮容器 Widget
    QWidget* toolsContainer = new QWidget();
    toolsContainer->setFixedHeight(45);
    layout->addWidget(toolsContainer);

    // 3.1 创建⼯具按钮的布局管理器.
    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setContentsMargins(10, 10, 0, 0);
    hlayout->setSpacing(0);
    hlayout->setAlignment(Qt::AlignLeft);
    toolsContainer->setLayout(hlayout);

    // 3.2 创建⼯具按钮
    QString buttonStyle = "QPushButton { background-color: transparent;\
                            border: none; } QPushButton:hover { background-color: #E1E1E1;}";
    QSize buttonSize(35, 35);
    QSize iconSize(25, 25);

    //发送图片按钮
    sendImageBtn = new QPushButton();
    sendImageBtn->setFixedSize(buttonSize);
    sendImageBtn->setIconSize(iconSize);
    sendImageBtn->setIcon(QIcon(":/images/send_image.png"));
    sendImageBtn->setStyleSheet(buttonStyle);
    hlayout->addWidget(sendImageBtn);

    //发送文件按钮
    sendFileBtn = new QPushButton();
    sendFileBtn->setFixedSize(buttonSize);
    sendFileBtn->setIconSize(iconSize);
    sendFileBtn->setIcon(QIcon(":/images/send_file.png"));
    sendFileBtn->setStyleSheet(buttonStyle);
    hlayout->addWidget(sendFileBtn);

    //发送声音按钮
    sendSoundBtn = new QPushButton();
    sendSoundBtn->setFixedSize(buttonSize);
    sendSoundBtn->setIconSize(iconSize);
    sendSoundBtn->setIcon(QIcon(":/images/send_sound.png"));
    sendSoundBtn->setStyleSheet(buttonStyle);
    hlayout->addWidget(sendSoundBtn);

    //查看历史消息按钮
    showHistoryBtn = new QPushButton();
    showHistoryBtn->setFixedSize(buttonSize);
    showHistoryBtn->setIconSize(iconSize);
    showHistoryBtn->setIcon(QIcon(":/images/show_history.png"));
    showHistoryBtn->setStyleSheet(buttonStyle);
    hlayout->addWidget(showHistoryBtn);

    // 4. 创建编辑框
    textEdit = new QPlainTextEdit();
    textEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    textEdit->setStyleSheet("QPlainTextEdit { border: none; background-color:transparent; font-size: 14px; padding: 10px; } ");
    textEdit->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width:2px; background-color: rgb(46, 46, 46); }");
    layout->addWidget(textEdit);

    // 5. 创建⼀个提⽰信息 label, 默认状态为隐藏
    tipLabel = new QLabel();
    tipLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    tipLabel->setText("录⾳中...");
    tipLabel->setAlignment(Qt::AlignCenter);
    tipLabel->setFont(QFont("微软雅⿊", 24, 600));
    layout->addWidget(tipLabel);
    tipLabel->hide();

    // 6. 创建发送按钮
    sendBtn = new QPushButton();
    sendBtn->setText("发送");
    sendBtn->setFixedSize(100, 35);
    QString style = "QPushButton { font-size: 16px; color: rgb(7, 193, 96);\
        border: none; background-color: rgb(233, 233, 233); border-radius: 10px; }";
    style += "QPushButton:hover { background-color: rgb(210, 210, 210); } ";
    style += "QPushButton:pressed { background-color: rgb(198, 198, 198);} ";
    sendBtn->setStyleSheet(style);
    layout->addWidget(sendBtn, 0, Qt::AlignRight | Qt::AlignVCenter);

    //绑定槽函数
    initSignalSlot();
}

void MessageEditArea::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);

    // 可以在这里添加自定义绘制代码
    QWidget::paintEvent(event);
}

void MessageEditArea::initSignalSlot()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    connect(sendBtn, &QPushButton::clicked, this, &MessageEditArea::sendTextMessage);

    connect(dataCenter, &model::DataCenter::sendMessageDone, this, &MessageEditArea::addSelfMessage);
    connect(dataCenter, &model::DataCenter::sendMessageFailed, this, [=](const QString& errmsg){
        QMessageBox::information(this, "提示", errmsg);
    });

    // 处理收到⽹络上来⾃别⼈的响应情况
    connect(dataCenter, &model::DataCenter::receiveMessageDone, this, &MessageEditArea::addOtherMessage);


    //查看历史消息
    connect(showHistoryBtn, &QPushButton::clicked, this, [=](){

        //获取到当前的会话id
        const QString& currentChatSessionId = model::DataCenter::getInstance()->getCurrentChatSessionId();
        if(currentChatSessionId == nullptr){
            return;
        }

        HistoryMessageWidget* dialog = new HistoryMessageWidget();
        dialog->show();
    });

}

void MessageEditArea::sendTextMessage()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    //如果未选中任何会话，则不发送消息
    if(dataCenter->getCurrentChatSessionId().isEmpty()){
        LOG() << "当前未选中会话, 不发送任何消息!";
        return;
    }

    //获取输入框中的内容，并去除前后空格
    QString content = textEdit->toPlainText().trimmed();
    if(content.isEmpty()){
        LOG() << "输⼊框为空, 不发送任何消息!";
        return;
    }

    //清空输入框
    textEdit->setPlainText("");

    //通过网络发送数据给服务器
    dataCenter->sendTextMessageAsync(dataCenter->getCurrentChatSessionId(), content);
}

void MessageEditArea::addSelfMessage(model::MessageType messageType, const QByteArray &content, const QString& extraInfo)
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    //构造消息对象并添加到消息列表中
    const model::Message& message = model::Message::makeMessage(messageType, dataCenter->getCurrentChatSessionId(), *dataCenter->getMyselfInfo(),content,extraInfo);
    dataCenter->addMessage(message);

    //向消息展示区中添加消息
    MainWidget* mainWidget = qobject_cast<MainWidget*>(owner);
    if (!mainWidget) {
        LOG() << "Owner is not a MainWidget!";
        return;
    }
    MessageShowArea* messageShowArea = mainWidget->getMessageShowArea();
    messageShowArea->addMessage(false, message);

    //设置消息显示区的滚动条滚动到末尾
    messageShowArea->scrollToEndLater();

    //更新会话列表的最后一条消息
    emit dataCenter->updateLastMessage(dataCenter->getCurrentChatSessionId());

}

void MessageEditArea::addOtherMessage(const model::Message &message)
{
    // 把这个消息显⽰到界⾯上
    MainWidget* mainWidget = dynamic_cast<MainWidget*>(owner);
    MessageShowArea* messageShowArea = mainWidget->getMessageShowArea();
    messageShowArea->addMessage(true, message);
    // 设置消息显⽰区的滚动条滚动到末尾
    messageShowArea->scrollToEndLater();
    // 提⽰收到⼀个消息
    //Toast::showMessage("收到⼀条新消息!");
    LOG() << "收到⼀条新消息";
}
